from DBUtils.PooledDB import PooledDB
import pymysql
import logging

#log格式定义
LOG_FORMAT = "%(asctime)s - tid:%(thread)d - %(filename)s[line:%(lineno)d] %(levelname)s - %(message)s"
DATE_FORMAT = "%m/%d/%Y %H:%M:%S %p"
#初始化日志库
def initLog(log_path):
        #logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=LOG_FORMAT, datefmt=DATE_FORMAT)
        #logging.basicConfig(filename='./my.log', level=logging.INFO, format=LOG_FORMAT, datefmt=DATE_FORMAT)
        logging.basicConfig(filename=log_path, level=logging.INFO, format=LOG_FORMAT, datefmt=DATE_FORMAT)


def mysql():
    MYSQL_HOST = '192.168.100.2'
    USER = 'jiangguoyou'
    PASSWORD = 'jiangguoyou'
    # MYSQL_HOST = '154.8.151.95'
    # USER = 'root'
    # PASSWORD = 'Mdst@123..'
    DB = 'drug'
    PORT = 3306
    db = PooledDB(pymysql, 5, host=MYSQL_HOST, user=USER, passwd=PASSWORD, db=DB, port=PORT)  # 5为连接池里的最少连接数
    return db

# 关闭连接
def mysql_close(cursor, conn):
    cursor.close()
    conn.close()

# 获取字段生成列表
def sql_index(cursor):
    sqltitle = []
    for key in cursor.description:
        title = key[0]
        sqltitle.append(title)
    return sqltitle
def sql_index_dict(cursor):
    sqldata = cursor.fetchall()
    sqltitle = sql_index(cursor)
    resdata = []
    for sqlvalue in sqldata:  # 循环重构每一条sql返回数据字典
        resdatai = {}
        # index为字段列表的下标，value为字段列表的值
        for index, value in enumerate(sqltitle):
            # data[title]为{}的key，sqlvalue[index]为{}的value--{"data[title]":"sqlvalue[index]"}
            resdatai[value] = sqlvalue[index]
        resdata.append(resdatai)  # 把{"data[title]":"sqlvalue[index]"}添加到resdata = []列表
    return resdata